﻿using BLL;
using InfoSoftGlobal;
using System;
using System.Data;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Thksoft.BusinessExpansion.StatisticalSum
{
    public partial class WeekSum : BaseUI.BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("YearNum", Type.GetType("System.String"));
                dt.Columns.Add("Year", Type.GetType("System.String"));
                object[] parm = new object[2];
                int ye = Convert.ToInt32(DateTime.Now.AddYears(-5).Year.ToString());
                for (int i = ye; i <= Convert.ToInt32(DateTime.Now.AddYears(5).Year.ToString()); i++)
                {
                    parm[0] = i;
                    parm[1] = i + "";
                    dt.Rows.Add(parm);
                }
                DropDownList1.DataSource = dt;
                DropDownList1.DataValueField = "YearNum";
                DropDownList1.DataTextField = "Year";
                DropDownList1.DataBind();
                DropDownList1.SelectedValue = DateTime.Now.Year.ToString();
                txtCompany.Text = "请选择公司";
                DropDownList2.SelectedValue = DateTime.Now.Month.ToString();
                //  this.hidCompanyId.Value = companyId2;
                //   Com_Name();
                TextChanged();
            }
        }

        /// <summary>
        /// 查询事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            //    gvReport.Attributes.Add("style", "table-layout:fixed");
            DataTable dt = getdatatable();
            if (dt != null && dt.Rows.Count > 0)
            {
                string str = "";
                int state = 0;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //上周资金计划
                    decimal sumOnWeek = 0;
                    //累计使用金额
                    decimal sumCumulativeWeek = 0;
                    //本周金额
                    decimal sumThisWeek = 0;

                    string ss = dt.Rows[i]["公司名称"].ToString() + "小计";
                    string xj = dt.Rows[i]["公司名称"].ToString();
                    if (str != dt.Rows[i]["公司名称"].ToString() && str != ss && !xj.Contains("小计"))
                    {
                        str = dt.Rows[i]["公司名称"].ToString();

                        DataRow[] db2 = dt.Select("公司名称='" + str + "' and 父级编号=0");
                        foreach (DataRow item in db2)
                        {
                            decimal va1 = Convert.ToDecimal(item["截止上周资金计划"] == "" ? "0" : item["截止上周资金计划"]);
                            decimal va2 = Convert.ToDecimal(item["截止上周累计资金"] == "" ? "0" : item["截止上周累计资金"]);
                            decimal va3 = Convert.ToDecimal(item["本周资金计划"] == "" ? "0" : item["本周资金计划"]);
                            sumThisWeek += va3;
                            sumCumulativeWeek += va2;
                            sumOnWeek += va1;
                            state = 0;
                        }
                    }
                    if (state == 0)
                    {
                        int index = 0;
                        for (int k = 0; k < dt.Rows.Count; k++)
                        {
                            if (dt.Rows[k]["公司名称"].ToString() == str)
                            {
                                index = k;
                            }
                        }
                        index += 1;
                        DataRow dr = dt.NewRow();
                        dt.Rows.InsertAt(dr, index);
                        dt.Rows[index][0] = str + "小计";
                        dt.Rows[index][1] = "小计";
                        dt.Rows[index][2] = sumOnWeek.ToString();
                        dt.Rows[index][3] = sumCumulativeWeek;
                        dt.Rows[index][4] = sumThisWeek.ToString();
                        state = 1;
                    }
                }
                //上周资金计划
                decimal OnWeek = 0;
                //本周资金计划
                decimal ThisWeek = 0;
                //上周资金计划使用累计
                decimal cumulativeWeek = 0;
                DataRow[] db = dt.Select("项目名称='小计'");
                foreach (DataRow item in db)
                {
                    decimal va1 = Convert.ToDecimal(item["截止上周资金计划"]);
                    decimal va2 = Convert.ToDecimal(item["截止上周累计资金"]);
                    decimal va3 = Convert.ToDecimal(item["本周资金计划"]);
                    OnWeek += va1;
                    ThisWeek += va3;
                    cumulativeWeek = va2;
                }

                int inde = dt.Rows.Count;
                DataRow dr2 = dt.NewRow();
                dt.Rows.InsertAt(dr2, inde);
                dt.Rows[inde][0] = "";
                dt.Rows[inde][1] = "总计";
                dt.Rows[inde][2] = OnWeek.ToString();
                dt.Rows[inde][3] = cumulativeWeek.ToString();
                dt.Rows[inde][4] = ThisWeek.ToString();
            }
            if (dt != null && dt.Rows.Count > 0)
            {
                DataRow[] drRows = dt.Select("项目名称='总计'");
                //求和
                decimal sum = 0;
                //平均值
                decimal avg = 0;
                //最大值
                decimal max = 0;
                //最小值
                decimal least = 0;

                foreach (DataRow item in drRows)
                {
                    sum += Convert.ToDecimal(item["截止上周资金计划"].ToString());
                    sum += Convert.ToDecimal(item["本周资金计划"].ToString());
                }

                decimal onWeekmax = Convert.ToDecimal(dt.Compute("Max(截止上周资金计划)", "").ToString());
                decimal thisWeekmax = Convert.ToDecimal(dt.Compute("Max(本周资金计划)", "").ToString());

                decimal onWeekLeast = Convert.ToDecimal(dt.Compute("min(截止上周资金计划)", "").ToString());
                decimal thisWeekLeast = Convert.ToDecimal(dt.Compute("min(本周资金计划)", "").ToString());

                if (onWeekmax > thisWeekmax)
                {
                    max = onWeekmax;
                }
                else
                {
                    max = thisWeekmax;
                }

                if (onWeekLeast > thisWeekLeast)
                {
                    least = thisWeekLeast;
                }
                else
                {
                    least = onWeekLeast;
                }
                avg = sum / Convert.ToDecimal(DropDownList3.SelectedValue);
                if (avg.ToString().Contains("."))
                {
                    if (avg.ToString().Substring(avg.ToString().LastIndexOf('.')).Length > 4)
                    {
                        avg = Convert.ToDecimal(avg.ToString().Substring(0, avg.ToString().LastIndexOf('.') + 5).ToString());
                    }
                }
                lblExplain.InnerHtml = "本月截至本周总金额：" + sum + "元&nbsp;平均每周" + avg + "元&nbsp;高峰期：" + max + "元&nbsp;低峰期：" + least + "元";
            }
            //lbltitle.InnerHtml = DropDownList1.SelectedValue + "年" + DropDownList2.SelectedValue + "月第" + DropDownList3.SelectedValue + "周资金统计";
            gvReport.DataSource = dt;
            gvReport.DataBind();

            if (dt != null && dt.Rows.Count > 0)
            {
                updateChart(); //画饼状图

                InitZzt();  //柱状图
                //折线图
                InitZXT();
                // this.imgZxt.ImageUrl = "~/ManagementPlatform/SignatureManage/weekZxt.aspx";
                lblExplain.Style.Add("display", "block;");
            }
            else
            {
                lblExplain.Style.Add("display", "none");
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public DataTable getdatatable()
        {
            //选择公司
            if (this.hidCompanyId.Value == "")
            {
                txtCompany.Text = "请选择公司";
                hidCompanyId.Value = "";
                MessageBox.Show(Page, "【温馨提示】请选择公司！");
                return null;
            }

            string str = "";
            string companyId = this.hidCompanyId.Value.ToString();
            string s = DropDownList1.SelectedValue.Trim().ToString();
            int mt = Convert.ToInt32(DropDownList2.SelectedValue.Trim().ToString());
            if (mt > 0 && mt < 10)
            {
                str += s + "0" + mt;
            }
            else
            {
                str = s + mt;
            }
            //打印传值
            string strval = companyId + "&" + str + "&" + DropDownList3.SelectedValue.Trim().ToString();
            this.printargs.Value = strval;

            DataTable dt = new Qs_Week_SonBLL().SelectReport(companyId, str, DropDownList3.SelectedValue.Trim().ToString());
            return dt;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvReport_PreRender(object sender, EventArgs e)
        {
            for (int rowIndex = gvReport.Rows.Count - 2; rowIndex >= 0; rowIndex--)
            {
                GridViewRow row = gvReport.Rows[rowIndex];
                GridViewRow previousRow = gvReport.Rows[rowIndex + 1];
                if (row.Cells[0].Text == previousRow.Cells[0].Text)
                {
                    row.Cells[0].RowSpan = previousRow.Cells[0].RowSpan < 2 ? 2 : previousRow.Cells[0].RowSpan + 1;
                    previousRow.Cells[0].Visible = false;
                }
            }
        }

        #region 导出方法

        protected void btnOutput_Click(object sender, EventArgs e)
        {
            string fileName = "周资金统计报表_" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
            string str = "导出人：" + CurrentUserName + "&nbsp;&nbsp;&nbsp;导出时间：" + DateTime.Now;
            lblTJ.Text = str;
            ExportExcel(pnl, fileName);
        }

        /// <summary>
        /// 导出方法
        /// </summary>
        /// <param name="objControl"></param>
        /// <param name="strFileName"></param>
        public void ExportExcel(System.Web.UI.WebControls.WebControl objControl, string strFileName)
        {
            strFileName = System.Web.HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8);
            System.Web.HttpContext.Current.Response.Clear();
            System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
            System.Web.HttpContext.Current.Response.Buffer = true;
            System.Web.HttpContext.Current.Response.Charset = "gb2312";
            System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + strFileName + ".xls");
            System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel";

            System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("zh-CN", true);
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

            objControl.RenderControl(oHtmlTextWriter);

            objControl = null;
            System.Web.HttpContext.Current.Response.Write(oStringWriter.ToString().Replace("<td", "<td STYLE='MSO-NUMBER-FORMAT:\\@'"));
            System.Web.HttpContext.Current.Response.Buffer = false;
            System.Web.HttpContext.Current.Response.Flush();
            System.Web.HttpContext.Current.Response.End();
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            //base.VerifyRenderingInServerForm(control);
        }

        #endregion 导出方法

        #region 画图

        /// <summary>
        /// 查询方法（画图）
        /// </summary>
        /// <returns></returns>
        public DataTable SelectDt()
        {
            //选择公司
            string companyId = this.hidCompanyId.Value.ToString(); //公司
            if (companyId == "")
            {
                MessageBox.Show(Page, "【温馨提示】请选择公司！");
                return null;
            }

            string s = DropDownList1.SelectedValue.Trim().ToString(); //获取年
            int mt = Convert.ToInt32(DropDownList2.SelectedValue.Trim().ToString());  //获取月
            string str = ""; //获取年月
            if (mt > 0 && mt < 10)
            {
                str += s + "0" + mt;
            }
            else
            {
                str = s + mt;
            }

            Session["week"] = companyId + "&" + s + "&" + mt;

            string sql = string.Format(@"select sum(tswkfund) 金额,week_num from (
            select CASE when s.m_id = 0 then
                  (select fd.pro_name from qs_fundplan fd where fd.pro_id = f.pro_id)
                 else
                  (select fm.projectname from qs_fundmonplan fm where fm.id = s.m_id)
                  end 项目名称,s.tswkfund,m.m_month,m.week_num, f.fatherid
            from qs_week_main m,qs_week_son s, qs_fundplan f,qs_business b
            where m.w_id=s.mian_id and f.pro_id=s.n_fundid and f.fatherid=0
            and b.n_business_id=m.n_business
            and b.n_business_state=2
            and m.n_company_id in (" + companyId + @")
            and m.m_month=" + str + @"
            and m.issave=1
            order by m.week_num
            ) group by week_num order by week_num");
            DataTable dt = new BaseBLL().Query(sql);

            //DataTable dt = new Qs_Week_SonBLL().SelectReport(companyId, str, DropDownList3.SelectedValue.Trim().ToString());
            return dt;
        }

        /// <summary>
        /// 画项目状态统计图(饼状图)
        /// </summary>
        private void updateChart()
        {
            DataTable dt = SelectDt();

            StringBuilder strXML = new StringBuilder();

            if (dt != null && dt.Rows.Count > 0)
            {
                strXML.Append("<chart caption='公司周资金饼状图'  shownames='1'  numberSuffix='元' baseFont='仿宋' baseFontSize='12' palette='1' formatNumberScale='0'>");
                int dy = Convert.ToInt32(Day(Convert.ToInt32(DropDownList2.SelectedValue.ToString()), Convert.ToInt32(DropDownList1.SelectedValue.ToString())));
                int count = getWeekCount(new DateTime(Convert.ToInt32(DropDownList1.SelectedValue.ToString()), Convert.ToInt32(DropDownList2.SelectedValue.ToString()), dy));
                int MonthInt = Convert.ToInt32(DropDownList2.SelectedValue.Trim().ToString());
                string MonthStr = MonthInt < 10 ? ("0" + MonthInt).ToString() : MonthInt.ToString();
                for (int k = 1; k <= count; k++)
                {
                    decimal jin_e = 0;
                    DataRow[] dr = dt.Select(" week_num = '" + (DropDownList1.SelectedValue.ToString() + MonthStr + k).ToString() + "'");
                    foreach (DataRow item in dr)
                    {
                        jin_e += Convert.ToDecimal(item["金额"].ToString());
                    }
                    strXML.AppendFormat("<set label='{0}' value='{1}'/>", "第" + k + "周", jin_e.ToString());
                }
                //for (int i = 0; i < dt.Rows.Count; i++)
                //{
                //    strXML.AppendFormat("<set label='{0}' value='{1}'/>", "第" + dt.Rows[i]["week_num"].ToString().Substring(6, 1) + "周", dt.Rows[i]["金额"].ToString());

                //}
                strXML.Append("</chart>");
                string outPut = "";

                outPut = FusionCharts.RenderChartHTML("../Flash/Pie3D.swf", "", strXML.ToString(), "billStatistics", "100%", "400", false, false);
                pnlChart.Controls.Clear();
                pnlChart.Controls.Add(new LiteralControl(outPut));
            }
        }

        /// <summary>
        /// 画项目柱状图
        /// </summary>
        public void InitZzt()
        {
            DataTable dt = SelectDt();

            StringBuilder strXML = new StringBuilder();
            if (dt != null && dt.Rows.Count > 0)
            {
                strXML.Append("<chart caption='公司本周资金柱状图' shownames='1'  numberSuffix='元' baseFont='仿宋' baseFontSize='12' palette='1' formatNumberScale='0'>");

                int dy = Convert.ToInt32(Day(Convert.ToInt32(DropDownList2.SelectedValue.ToString()), Convert.ToInt32(DropDownList1.SelectedValue.ToString())));
                int count = getWeekCount(new DateTime(Convert.ToInt32(DropDownList1.SelectedValue.ToString()), Convert.ToInt32(DropDownList2.SelectedValue.ToString()), dy));
                int MonthInt = Convert.ToInt32(DropDownList2.SelectedValue.Trim().ToString());
                string MonthStr = MonthInt < 10 ? ("0" + MonthInt).ToString() : MonthInt.ToString();
                for (int k = 1; k <= count; k++)
                {
                    decimal jin_e = 0;
                    DataRow[] dr = dt.Select(" week_num = '" + (DropDownList1.SelectedValue.ToString() + MonthStr + k).ToString() + "'");
                    foreach (DataRow item in dr)
                    {
                        jin_e += Convert.ToDecimal(item["金额"].ToString());
                    }
                    strXML.AppendFormat("<set label='{0}' value='{1}'/>", "第" + k + "周", jin_e.ToString());
                }
                strXML.Append("</chart>");
                string outPut = "";

                outPut = FusionCharts.RenderChartHTML("../Flash/Column3D.swf", "", strXML.ToString(), "billStatistics", "100%", "440", false, false);
                pnlZZT.Controls.Clear();
                pnlZZT.Controls.Add(new LiteralControl(outPut));
            }
        }

        /// <summary>
        /// 画项目折线图
        /// </summary>
        public void InitZXT()
        {
            DataTable dt = SelectDt();

            string year = DropDownList1.SelectedValue.Trim().ToString(); //获取年
            int mt = Convert.ToInt32(DropDownList2.SelectedValue.Trim().ToString());  //获取月
            string str = ""; //获取年月
            if (mt > 0 && mt < 10)
            {
                str += year + "0" + mt;
            }
            else
            {
                str = year + mt;
            }

            int dy = Convert.ToInt32(Day(Convert.ToInt32(mt), Convert.ToInt32(year)));  //某年某月有几天
            int count = getWeekCount(new DateTime(Convert.ToInt32(year), Convert.ToInt32(mt), dy));  //得到某年某月有几周
            StringBuilder strXML = new StringBuilder();

            if (dt != null && dt.Rows.Count > 0)
            {
                strXML.Append(@"<chart caption='公司周资金折线图' xAxisName='周数' yAxisName='金额（元）'    numberSuffix='元'  showValues='1' palette='2' shownames='1' legendBorderAlpha='0' useRoundEdges='1'
numdivlines='9' lineThickness='1' anchorRadius='2' anchorBgAlpha='10' showAlternateVGridColor='1' decimalPrecision='0' formatNumberScale='0' baseFont='仿宋' baseFontSize='12'>");

                strXML.Append("<categories>");
                for (int i = 0; i < count; i++)
                {
                    strXML.AppendFormat("<category label='第" + (i + 1) + "周'/>");
                }
                strXML.Append("</categories><dataset seriesName='周申请金额'>");
                float[] d = new float[count];
                //  string str = "201306";
                for (int i = 0; i < d.Length; i++)
                {
                    d[i] = float.Parse(dt.AsEnumerable().Where(s => s.Field<string>("week_num").ToString() == str + "" + (i + 1) + "").Sum(s => float.Parse(s.Field<decimal>("金额").ToString())).ToString());
                }
                for (int j = 0; j < count; j++)
                {
                    strXML.AppendFormat("<set value='{0}' displayValue='{1}' /> ", d[j].ToString(), d[j].ToString());
                }
                strXML.Append("</dataset>");
                strXML.Append("</chart>");

                string outPut = "";
                outPut = FusionCharts.RenderChartHTML("../FusionCharts/MSLine.swf", "", strXML.ToString(), "billStatistics", "100%", "440", false, false);
                pnlZXT.Controls.Clear();
                pnlZXT.Controls.Add(new LiteralControl(outPut));
            }
        }

        #endregion 画图

        #region 计算选择年月后有多少周

        #region 年

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            TextChanged();
        }

        #endregion 年

        #region 月

        protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
        {
            TextChanged();
        }

        #endregion 月

        #region 方法

        private void TextChanged()
        {
            DropDownList3.Items.Clear();
            int dy = Convert.ToInt32(Day(Convert.ToInt32(DropDownList2.SelectedValue.ToString()), Convert.ToInt32(DropDownList1.SelectedValue.ToString())));
            int count = getWeekCount(new DateTime(Convert.ToInt32(DropDownList1.SelectedValue.ToString()), Convert.ToInt32(DropDownList2.SelectedValue.ToString()), dy));
            DataTable dt = new DataTable();
            dt.Columns.Add("WeekNum", Type.GetType("System.String"));
            dt.Columns.Add("Week", Type.GetType("System.String"));
            object[] parm = new object[2];
            for (int i = 1; i <= count; i++)
            {
                parm[0] = i;
                parm[1] = "第" + i + "周";
                dt.Rows.Add(parm);
            }
            DropDownList3.DataSource = dt;
            DropDownList3.DataTextField = "Week";
            DropDownList3.DataValueField = "WeekNum";
            DropDownList3.SelectedValue = "1";
            DropDownList3.DataBind();
        }

        /// <summary>
        /// 某年某月共计有多少天
        /// </summary>
        /// <param name="Montha"></param>
        /// <param name="Yeara"></param>
        /// <returns></returns>
        private string Day(int Montha, int Yeara)
        {
            string day = "0";
            int[] str = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

            for (int i = 0; i < str.Count(); i++)
            {
                if (i == (Montha - 1))
                {
                    day = str[i].ToString();
                }
            }
            if (Montha == 2)
            {
                if (Yeara % 4 == 0 && Yeara % 100 != 0)
                {
                    day = "29";
                }
            }
            return day;
        }

        /// <summary>
        /// 得到当前月共有好多周
        /// </summary>
        private int getWeekCount(DateTime dt)
        {
            int currentWeek = 0;
            DateTime dd = new DateTime(dt.Year, dt.Month, 1);
            int xq = (int)dd.DayOfWeek;
            int t1 = 0;
            //当前月的1号不是星期天
            if (xq > 0)
            {
                currentWeek++;
                t1 = 7 - xq;
            }
            int t2 = (dt.Day - t1) % 7;
            int t3 = 0;
            if (t2 != 0)
            {
                t3 = (dt.Day - t1) / 7 + 1;
            }
            else
            {
                t3 = (dt.Day - t1) / 7;
            }
            currentWeek += t3;
            return currentWeek;
        }

        #endregion 方法

        #endregion 计算选择年月后有多少周

        protected void gvReport_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string str = e.Row.Cells[0].Text;
                str += "," + e.Row.Cells[1].Text;
                if (str.Contains("小计"))
                {
                    e.Row.Attributes.Add("style", "color:Blue");
                    e.Row.Cells[1].Text = "";
                }
                else if (str.Contains("总计"))
                {
                    e.Row.Attributes.Add("style", "color:red");
                }
                else
                {
                    e.Row.Attributes.Add("style", "color:Black");
                }
            }
        }

        /// <summary>
        /// GridView标题列排序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvReport_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sPage = e.SortExpression;
            string SortOrder, OrderDire;
            SortOrder = ViewState["SortOrder"] == null ? null : (string)ViewState["SortOrder"];
            OrderDire = ViewState["OrderDire"] == null ? null : (string)ViewState["OrderDire"];
            if (SortOrder == sPage)
            {
                if (OrderDire == "Desc")
                    OrderDire = "ASC";
                else
                    OrderDire = "Desc";
            }
            else
            {
                SortOrder = e.SortExpression;
                OrderDire = "ASC";
            }
            ViewState["SortOrder"] = SortOrder;
            ViewState["OrderDire"] = OrderDire;
            BindProjectName(true);
        }

        /// <summary>
        /// 绑定项目名称（非动态）绑定GridView
        /// </summary>
        public void BindProjectName(bool iSsort)
        {
            DataTable dt = getdatatable();
            if (dt != null && dt.Rows.Count > 0)
            {
                string str = "";
                int state = 0;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //上周资金计划
                    decimal sumOnWeek = 0;
                    //累计使用金额
                    decimal sumCumulativeWeek = 0;
                    //本周金额
                    decimal sumThisWeek = 0;

                    string ss = dt.Rows[i]["公司名称"].ToString() + "小计";
                    string xj = dt.Rows[i]["公司名称"].ToString();
                    if (str != dt.Rows[i]["公司名称"].ToString() && str != ss && !xj.Contains("小计"))
                    {
                        str = dt.Rows[i]["公司名称"].ToString();

                        DataRow[] db2 = dt.Select("公司名称='" + str + "' and 父级编号=0");
                        foreach (DataRow item in db2)
                        {
                            decimal va1 = Convert.ToDecimal(item["截止上周资金计划"] == "" ? "0" : item["截止上周资金计划"]);
                            decimal va2 = Convert.ToDecimal(item["截止上周累计资金"] == "" ? "0" : item["截止上周累计资金"]);
                            decimal va3 = Convert.ToDecimal(item["本周资金计划"] == "" ? "0" : item["本周资金计划"]);
                            sumThisWeek += va3;
                            sumCumulativeWeek += va2;
                            sumOnWeek += va1;
                            state = 0;
                        }
                    }
                    if (state == 0)
                    {
                        int index = 0;
                        for (int k = 0; k < dt.Rows.Count; k++)
                        {
                            if (dt.Rows[k]["公司名称"].ToString() == str)
                            {
                                index = k;
                            }
                        }
                        index += 1;
                        DataRow dr = dt.NewRow();
                        dt.Rows.InsertAt(dr, index);
                        dt.Rows[index][0] = str + "小计";
                        dt.Rows[index][1] = "小计";
                        dt.Rows[index][2] = sumOnWeek.ToString();
                        dt.Rows[index][3] = sumCumulativeWeek;
                        dt.Rows[index][4] = sumThisWeek.ToString();
                        state = 1;
                    }
                }
                //上周资金计划
                decimal OnWeek = 0;
                //本周资金计划
                decimal ThisWeek = 0;
                //上周资金计划使用累计
                decimal cumulativeWeek = 0;
                DataRow[] db = dt.Select("项目名称='小计'");
                foreach (DataRow item in db)
                {
                    decimal va1 = Convert.ToDecimal(item["截止上周资金计划"]);
                    decimal va2 = Convert.ToDecimal(item["截止上周累计资金"]);
                    decimal va3 = Convert.ToDecimal(item["本周资金计划"]);
                    OnWeek += va1;
                    ThisWeek += va3;
                    cumulativeWeek = va2;
                }

                int inde = dt.Rows.Count;
                DataRow dr2 = dt.NewRow();
                dt.Rows.InsertAt(dr2, inde);
                dt.Rows[inde][0] = "";
                dt.Rows[inde][1] = "总计";
                dt.Rows[inde][2] = OnWeek.ToString();
                dt.Rows[inde][3] = cumulativeWeek.ToString();
                dt.Rows[inde][4] = ThisWeek.ToString();
            }
            if (dt != null && dt.Rows.Count > 0)
            {
                DataRow[] drRows = dt.Select("项目名称='总计'");
                //求和
                decimal sum = 0;
                //平均值
                decimal avg = 0;
                //最大值
                decimal max = 0;
                //最小值
                decimal least = 0;

                foreach (DataRow item in drRows)
                {
                    sum += Convert.ToDecimal(item["截止上周资金计划"].ToString());
                    sum += Convert.ToDecimal(item["本周资金计划"].ToString());
                }

                decimal onWeekmax = Convert.ToDecimal(dt.Compute("Max(截止上周资金计划)", "").ToString());
                decimal thisWeekmax = Convert.ToDecimal(dt.Compute("Max(本周资金计划)", "").ToString());

                decimal onWeekLeast = Convert.ToDecimal(dt.Compute("min(截止上周资金计划)", "").ToString());
                decimal thisWeekLeast = Convert.ToDecimal(dt.Compute("min(本周资金计划)", "").ToString());

                if (onWeekmax > thisWeekmax)
                {
                    max = onWeekmax;
                }
                else
                {
                    max = thisWeekmax;
                }

                if (onWeekLeast > thisWeekLeast)
                {
                    least = thisWeekLeast;
                }
                else
                {
                    least = onWeekLeast;
                }
                avg = sum / Convert.ToDecimal(DropDownList3.SelectedValue);
                if (avg.ToString().Contains("."))
                {
                    if (avg.ToString().Substring(avg.ToString().LastIndexOf('.')).Length > 4)
                    {
                        avg = Convert.ToDecimal(avg.ToString().Substring(0, avg.ToString().LastIndexOf('.') + 5).ToString());
                    }
                }
                lblExplain.InnerHtml = "本月截至本周总金额：" + sum + "元&nbsp;平均每周" + avg + "元&nbsp;高峰期：" + max + "元&nbsp;低峰期：" + least + "元";
            }

            DataView view = dt.DefaultView;
            if (iSsort)
            {
                string sort = (string)ViewState["SortOrder"] + " " + (string)ViewState["OrderDire"];
                view.Sort = sort;//设置排序
            }

            gvReport.DataSource = view;

            gvReport.DataBind();
        }
    }
}